package com.ljk.config;

import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;

import java.io.File;
import java.util.Arrays;
import java.util.stream.Collectors;


@Command(name = "java -jar option-ctyun.jar", description = "请求示例", mixinStandardHelpOptions = true,
        sortOptions = false, version = "0.0.1", exitCodeOnVersionHelp = -1, exitCodeOnUsageHelp = -1)
@Getter
@Setter
@ToString
public class CtyunProperty implements Runnable {

    @Option(names = {"-ip","-point"}, description = "终端IP", required = true, paramLabel = "<x.oss.com>", order = 1)
    private String endpoint;
    @Option(names = {"-key"}, description = "账号AccessKeyId", required = true, paramLabel = "<key>", order = 2)
    private String accessKeyId;
    @Option(names = {"-secret"}, description = "秘钥SecretAccessKey", required = true, paramLabel = "<secret>", order = 3)
    private String accessKeySecret;
    @Option(names = {"-bucket"}, description = "桶名称", required = true, order = 4)
    private String bucketName;

    @Option(names = {"-f", "--file"}, description = "本地文件名", order = 5, required = true)
    private String file;
    @Option(names = {"-up", "-uploadFolder"}, description = "路径名", order = 6, paramLabel = "要上传的路径名,相对地址")
    private String uploadFolder;
    @Option(names = {"-newName"}, description = "如果需要指定上传的文件名,传入此参数", defaultValue = "", order = 7)
    private String rename;
    @Option(names = {"-o", "--option"}, description = "操作方式", order = 0, required = true)
    private String option;

    @Override
    public void run() {
        OptionEnum optionEnum = OptionEnum.get(option);
        if (optionEnum == null) {
            String collect = Arrays.stream(OptionEnum.values()).map(i -> i.toString() + "(" + i.getDesc() + ")").collect(Collectors.joining());
            throw new RuntimeException("未定义的操作,目前只开放了这些操作:" + collect);
        }
        File uploadFile = new File(file);
        if (!uploadFile.exists()) {
            throw new RuntimeException("文件不存在");
        }
        if (uploadFolder == null) {
            uploadFolder = "";
        } else {
            uploadFolder = uploadFolder.replace("\\", "/");
            uploadFolder = uploadFolder.replace("//", "/");
            uploadFolder = uploadFolder.startsWith("/") ? uploadFolder.substring(1) : uploadFolder;
            uploadFolder = uploadFolder.endsWith("/") ? uploadFolder.substring(0, uploadFolder.length() - 1) : uploadFolder;
        }
        if (StrUtil.isNotEmpty(rename) && rename.startsWith("/")) {
            rename = rename.substring(1);
        }

    }
}
